import { defineStore } from 'pinia';
import * as Sentry from '@sentry/vue';
import AUTH from 'src/api/auth.js';
import axios from 'axios';
import { useGlobalStore } from './global'; // 添加缺失的导入

const ACCESS_TOKEN_KEY = 'access'; // 保持存储键名不变
const REFRESH_TOKEN_KEY = 'refresh';
const USER_KEY = 'user';
const FRIEND_KEY = 'friend';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoading: false,
    refreshPromise: null, // 用于处理并发token刷新
  }),

  actions: {
    getFriend() {
      return JSON.parse(localStorage.getItem(FRIEND_KEY));
    },
    saveFriend(user) {
      localStorage.setItem(USER_KEY, JSON.stringify(user));
      localStorage.setItem(FRIEND_KEY, JSON.stringify(user));
    },
    removeFriend() {
      localStorage.removeItem(FRIEND_KEY);
    },

    getUser() {
      return JSON.parse(localStorage.getItem(USER_KEY));
    },
    saveUser(user) {
      localStorage.setItem(USER_KEY, JSON.stringify(user));
    },
    removeUser() {
      localStorage.removeItem(USER_KEY);
    },

    // 获取本地存储的JWT Token
    getAccessToken() {
      return localStorage.getItem(ACCESS_TOKEN_KEY);
    },

    getRefreshToken() {
      return localStorage.getItem(REFRESH_TOKEN_KEY);
    },

    // 保存认证信息
    saveAuthData(responseData) {
      // 使用解构重命名符合驼峰规则
      const {
        access: accessToken,
        refresh: refreshToken,
      } = responseData;

      localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
      localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);

      // 配置axios默认授权头
      axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
    },

    // 清除认证信息
    clearAuthData() {
      localStorage.removeItem(ACCESS_TOKEN_KEY);
      localStorage.removeItem(REFRESH_TOKEN_KEY);
      localStorage.removeItem(USER_KEY);
      delete axios.defaults.headers.common.Authorization;
      Sentry.configureScope((scope) => scope.setUser(null));
    },

    // Token自动刷新机制
    async refreshToken() {
      // 避免重复刷新
      if (this.refreshPromise) return this.refreshPromise;

      const refreshToken = this.getRefreshToken();
      if (!refreshToken) throw new Error('No refresh token available');

      this.refreshPromise = AUTH.refreshToken({
        refresh_token: refreshToken, // 适配后端参数命名
      })
        .then((response) => {
          this.saveAuthData(response.data);
          return response.data.access_token;
        })
        .finally(() => {
          this.refreshPromise = null;
        });

      return this.refreshPromise;
    },

    // 登录逻辑
    async login(credentials) {
      this.isLoading = true;
      try {
        const response = await AUTH.login(credentials);
        if (response.status === 200) {
          this.saveAuthData(response.data);
          this.router.push({ name: 'Home' });
          // Sentry用户跟踪
          const { user } = response.data;
          this.saveUser(user);
          this.saveFriend(user);
          Sentry.setUser({ id: user.id, username: user.username, email: user.email });
        }
        return response;
      } catch (err) {
        this.clearAuthData();
        throw err;
      } finally {
        this.isLoading = false;
      }
    },

    // 注册逻辑
    async register(data) {
      this.isLoading = true;
      try {
        const response = await AUTH.register(data);
        if (response.status === 201) {
          // await this.login({
          //   username: data.username,
          //   password: data.password,
          // });
          this.removeUser();
          this.clearAuthData();
          // 正确使用全局 store
          const globalStore = useGlobalStore();
          globalStore.updateMenu(false);
          this.router.push({ name: 'Login' });
        }
        return response;
      } finally {
        this.isLoading = false;
      }
    },

    // 退出登录
    async logout() {
      this.isLoading = true;
      try {
        const response = await AUTH.logout({ refresh: this.getRefreshToken() });
        this.removeUser();
        this.clearAuthData();
        // 正确使用全局 store
        const globalStore = useGlobalStore();
        globalStore.updateMenu(false);
        this.router.push({ name: 'Login' });
        return response;
      } finally {
        this.isLoading = false;
      }
    },
    // 其他方法保持类似结构，需要时添加token处理...
  },
});
